package com.ruoyi.khpx.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.khpx.utils.DeepSeekUitls;
import lombok.extern.slf4j.Slf4j;
import org.apache.hc.core5.http.ParseException;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.web.reactive.function.client.WebClientResponseException;
import reactor.core.publisher.Flux;

import java.io.IOException;
import java.util.Map;
import java.util.Objects;

@Slf4j
@RestController
public class ChatController {

    private WebClient webClient(){
        return  WebClient.builder()
                .defaultHeader("Content-Type", MediaType.APPLICATION_JSON_VALUE)
                .defaultHeader("Authorization", "Bearer "+ DeepSeekUitls.API_KEY) //令牌
                .baseUrl(DeepSeekUitls.API_URL) //请求地址
                .build();
    }
    @PostMapping(value = "/askDeepSeek",produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<String> askDeepSeek(@RequestBody Map<String, String> request) throws IOException, ParseException {
        String message = request.get("message");
        log.info(message);
        // 动态构建请求体
        String requestBody = String.format(

                "{\"language\":\"zh-CN\",\"model\": \"deepseek-chat\", \"messages\": [{\"role\": \"system\", \"content\": \"You are an assistant, please answer the user's questions in Chinese.\"},{\"role\": \"user\", \"content\": \"%s\"}], \"stream\": true}",
                message
        );

        return webClient().post()
                .accept(MediaType.TEXT_EVENT_STREAM) //接收text/event-stream流的数据
                .body(BodyInserters.fromObject(requestBody)) //参数
                .retrieve()
                .bodyToFlux(String.class) //输出格式
                .map(s -> {
                    if (!Objects.equals(s, "[DONE]")) {
                        JSONObject jo = JSON.parseObject(s).getJSONArray("choices").getJSONObject(0).getJSONObject("delta");
                        String content = s;
                        log.info(content);
                        if(content != null){
                            return content;
                        }
                    }
                    return "";
                })
                .onErrorResume(WebClientResponseException.class, ex -> Flux.just(ex.getResponseBodyAsString())) //请求失败
                .doFinally(signalType -> log.info("完成")); //请求完成后

    }
}

